<template>
  <div class="news-container">
    <!-- 查询表单 -->
    <el-form :inline="true" :model="queryForm" class="search-form">
      <el-form-item label="关键词">
        <el-input v-model="queryForm.keyword" placeholder="请输入标题或日期(YYYY-MM-DD)" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">查询</el-button>
        <el-button type="success" @click="handleAdd">新增</el-button>
      </el-form-item>
    </el-form>

    <!-- 新闻表格 -->
    <div class="table-container">
      <el-table :data="newsList" border style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="ID" width="120" />
        <el-table-column prop="title" label="标题" min-width="220" />
        <el-table-column prop="createTime" label="创建日期" width="160" />
        <el-table-column label="操作" width="220">
          <template #default="scope">
            <div class="action-buttons">
              <el-button size="small" @click="handleView(scope.row)">查看</el-button>
              <el-button size="small" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :current-page="pagination.current"
        :page-size="pagination.size"
        :page-sizes="[5, 10, 20, 50]"
        :total="pagination.total"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="50%">
      <el-form ref="form" :model="form" :rules="rules" label-width="84px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input v-model="form.content" type="textarea" :rows="8" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" :loading="loading" @click="submitForm">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog title="新闻详情" v-model="detailVisible" width="50%">
      <div v-if="currentNews">
        <p><strong>ID:</strong> {{ currentNews.id }}</p>
        <p><strong>标题:</strong> {{ currentNews.title }}</p>
        <p><strong>创建日期:</strong> {{ currentNews.createTime }}</p>
        <p><strong>内容:</strong></p>
        <el-scrollbar max-height="300px">
          <div class="content" v-html="formatContent(currentNews.content)"></div>
        </el-scrollbar>
      </div>
      <div v-else>加载中...</div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailVisible = false">关 闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getNewsList, addNews, updateNews, deleteNews } from '@/api/newsApi'

export default {
  name: 'NewsManagementComponent',
  data() {
    return {
      queryForm: {
        keyword: ''
      },
      newsList: [],
      pagination: {
        current: 1,
        size: 10
      },
      form: {
        id: '',
        title: '',
        content: ''
      },
      rules: {
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        content: [{ required: true, message: '请输入内容', trigger: 'blur' }]
      },
      dialogVisible: false,
      dialogTitle: '',
      detailVisible: false,
      currentNews: null,
      loading: false
    }
  },
  // 创建完毕
  mounted() {
    this.fetchNewsList()
  },
  methods: {
    formatContent(text = '') {
      return (text || '').replace(/\n/g, '<br/>')
    },
    // 查询
    handleQuery() {
      this.pagination.current = 1
      this.fetchNewsList()
    },
    // 获取新闻列表
    async fetchNewsList() {
      this.loading = true
      try {
        const params = {
          keyword: this.queryForm.keyword,
          pageNum: this.pagination.current,
          pageSize: this.pagination.size
        }
        
        const res = await getNewsList(params)
        console.log('news query res:', res)
        
        // 处理后端返回的新闻数据
        // 根据数据库结构，createTime是字符串类型，不需要特殊转换
        if (res) {
          // 如果res是数组，直接使用
          if (Array.isArray(res)) {
            this.newsList = res.map(item => ({
              ...item,
              // 确保createTime正确显示
              createTime: item.createTime || ''
            }))
            this.pagination.total = res.length
          } 
          // 如果res包含data字段
          else if (res.data) {
            // 如果data是数组，直接使用
            if (Array.isArray(res.data)) {
              this.newsList = res.data.map(item => ({
                ...item,
                // 确保createTime正确显示
                createTime: item.createTime || ''
              }))
              this.pagination.total = res.total || res.data.length
            } 
            // 如果data包含嵌套的data数组（分页结构）
            else if (res.data.data && Array.isArray(res.data.data)) {
              this.newsList = res.data.data.map(item => ({
                ...item,
                // 确保createTime正确显示
                createTime: item.createTime || ''
              }))
              this.pagination.total = res.data.total || res.total || res.data.data.length
            } 
            // 其他情况
            else {
              this.newsList = []
              this.pagination.total = 0
            }
          } 
          // 其他情况
          else {
            this.newsList = []
            this.pagination.total = 0
          }
        } else {
          this.newsList = []
          this.pagination.total = 0
        }
      } catch (e) {
        console.error('获取新闻列表失败:', e)
        this.$message.error('获取新闻列表失败: ' + (e.message || '未知错误'))
        this.newsList = []
        this.pagination.total = 0
      } finally {
        this.loading = false
      }
    },
    // 获取新闻列表
    handleAdd() {
      this.dialogTitle = '新增新闻'
      this.form = { 
        id: '', 
        title: '', 
        content: '',
        createTime: '' // 添加createTime字段
      }
      this.dialogVisible = true
    },
    // 编辑
    handleEdit(row) {
      this.dialogTitle = '编辑新闻'
      this.form = { 
        id: row.id, 
        title: row.title || '', 
        content: row.content || '',
        createTime: row.createTime || '' // 保留createTime字段
      }
      this.dialogVisible = true
    },
    // 删除
    async submitForm() {
      try {
        if (!this.$refs.form) return
        const valid = await this.$refs.form.validate()
        if (!valid) return
        this.loading = true
        if (this.form.id) {
          // 更新新闻
          await updateNews(this.form)
          this.$message.success('更新成功')
        } else {
          // 新增新闻
          await addNews(this.form)
          this.$message.success('新增成功')
        }
        this.dialogVisible = false
        this.fetchNewsList()
      } catch (e) {
        console.error('操作失败:', e)
        this.$message.error('操作失败: ' + (e.message || '请重试'))
      } finally {
        this.loading = false
      }
    },
    // 确定
    handleView(row) {
      this.currentNews = row
      this.detailVisible = true
    },
    // 处理分页大小改变
    handleSizeChange(size) {
      this.pagination.size = size
      this.fetchNewsList()
    },
    // 处理分页页码改变
    handleCurrentChange(current) {
      this.pagination.current = current
      this.fetchNewsList()
    }
  }
}
</script>

<style scoped>
.news-container { padding: 16px; }
.search-form { margin-bottom: 16px; }
.table-container { background: #fff; }
.pagination-container { margin-top: 12px; text-align: right; }
.action-buttons { display: flex; gap: 8px; }
.content { white-space: normal; line-height: 1.6; }
</style> 